class AccountService
  
  def initialize(map)
    @map = map
  end
  
  def create
    external_subscription_id = -1 
        
    begin
      response = zgateway.recurring(charge_amount, credit_card, recurring_options)
    
      if response.success?
        external_subscription_id = response.authorization
      else
        GatewayResponse.create!(:message => response.message, 
                                :email   => @map[:email],  
                                :code    => response.params["code"] )
      end
    rescue => e
      logger.info("AccountService failed due to : #{e.inspect}")
      GatewayResponse.create!(:message => e.inspect)
    end
    
    external_subscription_id
  end
  # TODO: Lookup subscription_id based on who is logged in, amount from pricing table
  def update
  # @gateway.update_recurring(:subscription_id => subscription_id, :amount => @amount * 2)    
  end
  # TODO: Lookup subscription_id based on who is logged in
  def destroy
  # @gateway.cancel_recurring(subscription_id)    
  end
  
  def credit_card
    ActiveMerchant::Billing::CreditCard.new(
      :number     => @map[:credit_card_number], 
      :month      => @map[:expiration_month], 
      :year       => @map[:expiration_year], 
      :first_name => @map[:first_name], 
      :last_name  => @map[:last_name] 
    )
  end
  
  def recurring_options
    {
      :subscription_name => "Quarterly or Yearly values from form", 
      :billing_address => {
                            :first_name => @map[:first_name], 
                            :last_name  => @map[:last_name], 
                            :address1   => @map[:billing_address], 
                            :city       => @map[:billing_city], 
                            :state      => @map[:billing_state], 
                            :country    => "US", 
                            :zip        => @map[:billing_zip], 
                          }, 
      :interval => { 
                      :length => @map[:interval],  
                      :unit   => :months  
                   }, 
      :duration => { 
                      :start_date  => Time.now.utc.strftime("%Y-%m-%d"), 
                      :occurrences => 1000   
                   }, 
    }
  end
  # TODO : Amount should come from pricing table 
  # Load the value from the db here for the logged in user based on subscription plan
  def charge_amount
    22000
  end
end
